<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户昵称" prop="aliasName">
        <el-input
            v-model="queryParams.aliasName"
            placeholder="请输入用户昵称"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="20" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="用户账号" align="center" key="userName" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
      <el-table-column label="用户昵称" align="center" key="aliasName" prop="aliasName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
                type="primary"
                link
                icon="Edit"
                @click="handleUpdate(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.id !== 'admin'">
            <el-button
                type="primary"
                link
                icon="Delete"
                @click="handleDelete(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="重置密码" placement="top" v-if="scope.row.id !== 'admin'">
            <el-button
                type="primary"
                link
                icon="Key"
                @click="handleResetPwd(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNumber"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="成员名称" prop="staffName">
              <el-input v-model="form.staffName" placeholder="请选择成员" >
                <template #append>
                  <el-button :icon="Search" @click="openStaff" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="aliasName">
              <el-input v-model="form.aliasName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.userRoles" multiple placeholder="请选择">
                <el-option
                    v-for="item in roleOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="userName">
              <el-input v-model="form.userName" :readonly="form.id !== undefined" placeholder="请输入用户账号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.id === undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查询成员对话框 -->
    <el-dialog title="选择关联的成员" v-model="openStaffList" width="800px" append-to-body>
      <el-form :model="queryStaffParams" ref="queryStaffRef" :inline="true" v-show="showStaffSearch" label-width="68px">
        <el-form-item label="成员名称" prop="staffName">
          <el-input
              v-model="queryStaffParams.staffName"
              placeholder="请输入用户昵称"
              clearable
              style="width: 240px"
              @keyup.enter="handleStaffQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleStaffQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetStaffQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
          v-loading="loading"
          :data="staffList"
          ref="staffTable"
          highlight-current-row
          @current-change="handleCurrentChange"
          @row-click="clickStaff" @row-dblclick="clickDbStaff">
<!--        <el-table-column type="selection" width="50" align="center" />-->
        <el-table-column label="成员编号" align="center" key="staffCode" prop="staffCode" />
        <el-table-column label="成员名称" align="center" key="staffName" prop="staffName" />
        <el-table-column label="所属部门" align="center" :formatter="deptFormatter" />
        <el-table-column label="所属公司" align="center" :formatter="companyFormatter" />
      </el-table>
      <pagination
          v-show="staffTotal > 0"
          :total="staffTotal"
          v-model:page="queryStaffParams.pageNumber"
          v-model:limit="queryStaffParams.pageSize"
          @pagination="getStaffList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitStaffForm">确 定</el-button>
          <el-button @click="cancelStaff">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import {useRouter} from "vue-router";
import {getCurrentInstance, reactive, toRefs} from "vue";
// noinspection NpmUsedModulesInstalled,ES6UnusedImports
import { Search } from '@element-plus/icons-vue'
import {delUser, listUser, resetUserPwd, getUser, listRole, saveUser} from "../../../api/ac/ac"
import {getStaff, listAllDept, listCompany, listDept, listStaff} from "../../../api/ab/ab";

const router = useRouter()
const { proxy } = getCurrentInstance()

const currentStaffRow = ref()
const userList = ref([])
const staffList = ref([])
const deptList = ref([])
const companyList = ref([])
const open = ref(false)
const openStaffList = ref(false)
const loading = ref(true);
const showSearch = ref(true)
const showStaffSearch = ref(true)
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const staffTotal = ref(0)
const title = ref("");
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const initPassword = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);

// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户账号`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNumber: 1,
    pageSize: 10,
    aliasName: undefined
  },
  queryStaffParams: {
    pageNumber: 1,
    pageSize: 10,
    staffName: undefined
  },
  rules: {
    userName: [{ required: true, message: "用户名称不能为空", trigger: "blur" }, { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" }],
    aliasName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
    password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }, { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }],
  }
});

const { queryParams, queryStaffParams, form, rules } = toRefs(data);


/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then(res => {
    loading.value = false
    userList.value = res.ds.content
    total.value = res.ds.totalElements
  });
}
function getRoleList() {
  listRole({isPage:false}).then(res => {
    roleOptions.value = res.ds.content
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNumber = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
    return delUser(userIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleResetPwd":
      handleResetPwd(row);
      break;
    case "handleAuthRole":
      handleAuthRole(row);
      break;
    default:
      break;
  }
}
/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
  }).then(({ value }) => {
    resetUserPwd(row.id, value).then(response => {
      proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
    });
  }).catch(() => {});
}
/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
/** 重置操作表单 */
function reset() {
  form.value = {
    id: undefined,
    userName: undefined,
    aliasName: undefined,
    password: undefined,
    enabled: true,
    userRoles: []
  };
  proxy.resetForm("userRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户";
  form.value.password = initPassword.value;
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const userId = row.id || ids.value;
  getUser(userId).then(res => {
    form.value = res.ds;
    open.value = true;
    title.value = "修改用户";
    form.password = "";
    if(res.ds.staffId !== null && res.ds.staffId !== undefined && res.ds.staffId !== "") {
      getStaff(res.ds.staffId).then(staffRes => {
        form.value.staffName = staffRes.ds.staffName
      });
    }
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      saveUser(form.value).then(response => {
        if (form.value.id !== undefined) {
          proxy.$modal.msgSuccess("修改成功");
        } else {
          proxy.$modal.msgSuccess("新增成功");
        }
        open.value = false;
        getList();
      })
    }
  })
}

function handleCurrentChange(currentRow, oldCurrentRow) {
  currentStaffRow.value = currentRow
}

/** 单击  */
function clickStaff(row, column, event) {

}

/** 双击  */
function clickDbStaff(row, column, event) {
  form.value.staffId = row.id
  form.value.staffName = row.staffName
  form.value.aliasName = row.staffName
  openStaffList.value = false
}
/** 重置按钮操作 */
function resetStaffQuery() {
  proxy.resetForm("queryStaffRef");
  handleStaffQuery();
}
/** 搜索按钮操作 */
function handleStaffQuery() {
  queryStaffParams.value.pageNumber = 1
  getStaffList()
}
function openStaff() {
  // 查询所有公司
  getDeptList()
  // 查询所有部门
  getCompanyList()
  // 查询成员
  getStaffList()
  openStaffList.value = true
}
function deptFormatter(row, column) {
  if(row.department.length > 0) {
    for(let i = 0; i < deptList.value.length; i++) {
      if(deptList.value[i].id === row.department[0]) {
        return deptList.value[i].deptName
      }
    }
  }
}
function companyFormatter(row, column) {
  for(let i = 0; i < companyList.value.length; i++) {
    if(companyList.value[i].id === row.companyId) {
      return companyList.value[i].companyName
    }
  }
}
/** 查询部门列表 */
function getDeptList() {
  listAllDept().then(res => {
    deptList.value = res.ds
  })
}
function getCompanyList() {
  listCompany({isPage:false}).then(res => {
    companyList.value = res.ds.content
  })
}
function getStaffList() {
  listStaff(proxy.addDateRange(queryStaffParams.value, dateRange.value)).then(res => {
    loading.value = false
    staffList.value = res.ds.content
    staffTotal.value = Number(res.ds.totalElements)
  });
}
function submitStaffForm() {
  if(currentStaffRow.value === undefined || currentStaffRow.value === null) {
    proxy.$modal.msgWarning("请选择关联的成员");
    return
  }
  form.value.staffId = currentStaffRow.value.id
  form.value.staffName = currentStaffRow.value.staffName
  form.value.aliasName = currentStaffRow.value.staffName
  openStaffList.value = false
}
function cancelStaff() {
  openStaffList.value = false
}
getRoleList();
getList();
</script>
